package com.pb.camera;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.pb.camera.application.App;
import com.pb.camera.helper.JsonHelper;
import com.pb.camera.utils.Constants;
import com.pb.camera.utils.JsonAnalyle;
import com.pb.camera.utils.MyTextWatcher;
import com.pb.camera.utils.RegexValidateUtil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class VerrificationCodeActivity extends Activity {
	private EditText edit_phone_num;
	private EditText edit_code;
	private ImageView image;
	private Timer timer;
	private TimerTask task;
	private TextView textView_timer;
	private String phoneNum;
	private String log_or_find = "log";
	private LinearLayout line_sendcode;
	private HttpUtils httpUtils;
	private Handler handler = new Handler() {
		// 条件区分的很不好啊
		public void handleMessage(Message msg) {
			if (msg.arg2 == 6) {
				Toast.makeText(VerrificationCodeActivity.this,
						(String) msg.obj, Toast.LENGTH_SHORT).show();
			} else if (msg.what == 10086) {
				if (timer != null && task != null) {
					try {
						timer.schedule(task, 0, 1000);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			} else if (msg.arg1 != 0) {
				textView_timer.setText(msg.arg1 + "秒后重新发送");
				line_sendcode.setClickable(false);
			} else if (msg.arg1 == 0) {
				textView_timer.setText("重新发送");
				line_sendcode.setClickable(true);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.phone_verrification_code);
		httpUtils = new HttpUtils();
		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
		App.getInstance().getAllActivity().add(this);
		// 若是空的话

		initView();
	}

	private void initView() {
		final View view=findViewById(R.id.phone_verrification_rela);
		final int height= App.getInstance().getStatusBarHeight(this);
        view.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {					
			@Override
			public boolean onPreDraw() {
				// TODO Auto-generated method stub
				view.setPadding(0, height, 0, 0);
				view.getViewTreeObserver().removeOnPreDrawListener(this);
				return true;
			}
		});
		log_or_find = getIntent().getExtras().getString("log_or_find");
		edit_phone_num = (EditText) findViewById(R.id.verrification_edit_account);
		edit_code = (EditText) findViewById(R.id.verrification_edit_code);
		image = (ImageView) findViewById(R.id.verrification_image_reset_phonenum);
		edit_phone_num.addTextChangedListener(new MyTextWatcher(edit_phone_num,
				image));
		textView_timer = (TextView) findViewById(R.id.verrification_textviwe_timer);
		line_sendcode = (LinearLayout) findViewById(R.id.verrification_line_sendcode);

	}

	public void verrification_onClick(View view) {
		switch (view.getId()) {
		case R.id.verrification_linear_rootview_:
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
			break;

		case R.id.verrification_image_back:
			finish();
			break;
		case R.id.verrification_line_sendcode:
			// 验证电话号码并发送验证码
			sendVerrificationCode(view);
			break;
		case R.id.verrification_line_next:	      
			if (!RegexValidateUtil.checkMobileNumber(edit_phone_num.getText()
					.toString())) {
			     Toast.makeText(VerrificationCodeActivity.this, "电话号码的格式不对", Toast.LENGTH_SHORT).show();
			     return;
			} else if(RegexValidateUtil.checkVerrificationCode(edit_code.getText().toString()))
			{
				Toast.makeText(VerrificationCodeActivity.this, "验证码格式不对", Toast.LENGTH_SHORT).show();
			}else{
				if (log_or_find.equals("log")) {
					getCode(Constants.compareCodeUrl(edit_phone_num.getText()
							.toString(), edit_code.getText().toString()), this,
							log_or_find, 0);

				} else if (log_or_find.equals("find")) {
					getCode(Constants.findPassword2(edit_phone_num.getText()
							.toString(), edit_code.getText().toString()), this,
							log_or_find, 0);
				}
			}
			break;
		}
	}

	// 但是需要验证电话号的格式
	private void sendVerrificationCode(final View view) {
		if (!RegexValidateUtil.checkMobileNumber(edit_phone_num.getText()
				.toString())) {
			Log.i("123", "手机格式不对");
		     Toast.makeText(VerrificationCodeActivity.this, "电话号码的格式不对", Toast.LENGTH_SHORT).show();
		     return;
		} else { // 保存电话号码
			Log.i("123", "手机格式正确");
			phoneNum = edit_phone_num.getText().toString();
			if (timer != null) {
				// 防止多次点击获取验证码
				view.setClickable(false);
			} else {
				timer = new Timer();
				view.setClickable(false);
			}
			task = new TimerTask() {
				private int time = 60;
				@Override
				public void run() {
					// TODO Auto-generated method stub
					time--;
					Message mes = Message.obtain();
					if (mes == null) {
						mes = new Message();
					}
					mes.arg1 = time;
					handler.sendMessage(mes);
					// textView_timer.setText(time+"秒后重新发送");
					if (time == 0) {
						cancel();
					}
				}
			};
			// timer.schedule(task, 0, 1000);
			// 获取短息的验证码的代码位置
			if (log_or_find.equals("log")) {
				getCode(Constants.getCodeUrl(edit_phone_num.getText()
						.toString(), "1"), this, "log", 1);
			} else if (log_or_find.equals("find")) {
				getCode(Constants.getCodeUrl(edit_phone_num.getText()
						.toString(), "0"), this, "log", 1);
			}

		}
	}

	private void getCode(String url, final Activity activity,
			final String mode, final int get_or_cpmpare) {
		httpUtils.send(HttpMethod.POST, url, new RequestCallBack<String>() {
			@Override
			public void onFailure(HttpException arg0, String arg1) {
				Toast.makeText(activity, "请求失败", 0).show();
				if (mode.equals("log") && get_or_cpmpare == 1) {
					line_sendcode.setClickable(true);
				} else if (mode.equals("find") && get_or_cpmpare == 1) {
					line_sendcode.setClickable(true);
				}
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// Map map=JsonHelper.jsonStringToMap(arg0.result,new
				// String[]{"errcode","errmsg"} , null);
				// 发出提示信息
				Log.i("123", "找回密码"+arg0.result);
				boolean flag = JsonAnalyle.jsonAnalyse(arg0.result,
						VerrificationCodeActivity.this, null, handler);
				if (flag) { // 代表的是注册,
					// 并且输入的验证码正确的时候
					if (mode.equals("log") && get_or_cpmpare == 0) {
						Bundle bundle = new Bundle();
						bundle.putString("mobile", edit_phone_num.getText()
								.toString());
						Intent intent = new Intent(
								VerrificationCodeActivity.this,
								SettingPasswordActivity.class);
						intent.putExtras(bundle);
						startActivity(intent);
					} else if (mode.equals("find") && get_or_cpmpare == 0) {
						// 代表的是找回密码
						// ,并且输入的验证码是正确的时候
						Intent intent = new Intent(
								VerrificationCodeActivity.this,
								FindPasswordActivity.class);
						startActivity(intent);
					} else if (mode.equals("log") && get_or_cpmpare == 1) {
						handler.sendEmptyMessage(10086);
						Log.i("123", "log与10086");
					} else if (mode.equals("find") && get_or_cpmpare == 1) {
						handler.sendEmptyMessage(10086);
						Log.i("123", "find与10086");
					}
				} else if (!flag) {
					// 获取验证码失败的,可能是手机号注册过了
					if (mode.equals("log") && get_or_cpmpare == 1) {
						line_sendcode.setClickable(true);
					} else if (mode.equals("find") && get_or_cpmpare == 1) {
						line_sendcode.setClickable(true);
					}
				}
			}
		});
	}

	@Override
	public void finish() {
		App.getInstance().getAllActivity().remove(this);
		super.finish();
	}

	@Override
	protected void onDestroy() {
		App.getInstance().getAllActivity().remove(this);
		super.onDestroy();
	}
}
